package com.meida.module.virbox.provider.tokenProvider.jwt;

import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.JsonUtils;
import com.meida.module.virbox.provider.entity.AuthToken;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * <b>功能名：H265JwtUtils</b><br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2021 HUIFANEDU  CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2022-02-14 jiabing
 */
public class H265JwtUtils {
    public static String salt = "VTJGc2RHVmtYMS9YV1JnRnZ2QUdDTWdNekZNZFdVNWg0OTIrZjVYanpqTT0";
    private static final  String MAC_INSTANCE_NAME = "HMacSHA256";
    public static String Hmacsha256(String secret, String message) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac hmac_sha256 = Mac.getInstance(MAC_INSTANCE_NAME);
        SecretKeySpec key = new SecretKeySpec(secret.getBytes(), MAC_INSTANCE_NAME);
        hmac_sha256.init(key);
        byte[] buff = hmac_sha256.doFinal(message.getBytes());
        return Base64.encodeBase64URLSafeString(buff);
    }
    public static String paseJWT(String sec,String jwt)throws Exception{
        ApiAssert.isNotEmpty("授权码不能为空",jwt);
        ApiAssert.isNotEmpty("机器码不能为空",sec);
        String[] arr = jwt.split("\\.");
        if(arr.length<3){
            ApiAssert.failure("授权码格式不正确");
        }

        String header = arr[0];
        String claim = arr[1];
        String signature = arr[2];

        String parseSign = H265JwtUtils.Hmacsha256(sec+salt,header+"."+claim);
        if(!signature.equals(parseSign)){
            ApiAssert.failure("授权码不正确");
        }
        return new String(Base64.decodeBase64(claim));

    }
    public static void main(String[] args)throws Exception{
        H265JwtUtils.paseJWT("36XW7SS55GD4D3NDG1HDFGS4887SVTJGc2RHVmtYMS9YV1JnRnZ2QUdDTWdNekZNZFdVNWg0OTIrZjVYanpqTT0","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJxekNvdW50IjoxLCJ1c2VyQ291bnQiOjAsImNhdGVnb3J5Q291bnQiOjAsImNhdGVnb3J5QWN0Q291bnQiOjAsImNvbXBhbnlDb3VudCI6MCwiYXV0aFRpbWUiOiIwIiwib25saW5lQ291bnQiOjAsImV4cGlyZWRUaW1lIjoiMTY0NDgzMTgyMyJ9.Ta4QckQzUQxj0DPMv5TzSxgbWGuyIrHSQvLUJuBYAFo");
    }
}   